<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="checkout-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>退租申请</h2>
        <el-button type="primary" @click="showApplyDialog = true" icon="Plus">申请退租</el-button>
      </div>

      <!-- 退租申请列表 -->
      <div class="checkout-list">
        <el-card v-for="item in checkoutList" :key="item.checkoutId" class="checkout-item">
          <div class="checkout-header">
            <div class="contract-info">
              <h3>合同编号: {{ item.contractId }}</h3>
              <p><strong>申请日期：</strong>{{ formatDate(item.applyDate) }}</p>
            </div>
            <div class="status-badge">
              <el-tag :type="getStatusType(item.checkoutStatus)">
                {{ getStatusText(item.checkoutStatus) }}
              </el-tag>
            </div>
          </div>
          
          <div class="checkout-content-detail">
            <p><strong>退租原因：</strong>{{ item.checkoutReason }}</p>
          </div>
          
          <div class="checkout-actions" v-if="item.checkoutStatus === 0">
            <el-button size="small" @click="viewDetail(item)">查看详情</el-button>
          </div>
        </el-card>
        
        <el-empty v-if="checkoutList.length === 0" description="暂无退租申请" />
      </div>

      <!-- 申请退租对话框 -->
      <el-dialog v-model="showApplyDialog" title="申请退租" width="600px">
        <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="120px">
          <el-form-item label="选择合同" prop="contractId">
            <el-select v-model="applyForm.contractId" placeholder="请选择要退租的合同" style="width: 100%">
              <el-option
                v-for="contract in activeContracts"
                :key="contract.contractId"
                :label="`${contract.house?.houseSummary} (${contract.startDate} - ${contract.endDate})`"
                :value="contract.contractId"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="退租原因" prop="checkoutReason">
            <el-input
              v-model="applyForm.checkoutReason"
              type="textarea"
              :rows="4"
              placeholder="请详细说明退租原因"
            />
          </el-form-item>
          
          <el-form-item label="期望退租日期" prop="expectedCheckoutDate">
            <el-date-picker
              v-model="applyForm.expectedCheckoutDate"
              type="date"
              placeholder="选择期望退租日期"
              style="width: 100%"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="applyForm.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
          
          <el-form-item label="紧急联系人">
            <el-input v-model="applyForm.emergencyContact" placeholder="请输入紧急联系人" />
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input v-model="applyForm.remarks" placeholder="其他说明" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="showApplyDialog = false">取消</el-button>
          <el-button type="primary" @click="submitApplication" :loading="submitting">提交申请</el-button>
        </template>
      </el-dialog>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import UserLayout from '@/components/layout/UserLayout.vue'
import api from '@/utils/api'
import { getToken } from '@/utils/auth'

const activeIndex = ref('4')
const activeMenu = ref('tenant')

// 退租申请列表
const checkoutList = ref([])
const loading = ref(false)

// 申请对话框
const showApplyDialog = ref(false)
const submitting = ref(false)
const applyFormRef = ref()

// 有效合同列表
const activeContracts = ref([])

// 申请表单
const applyForm = ref({
  contractId: '',
  checkoutReason: '',
  expectedCheckoutDate: '',
  contactPhone: '',
  emergencyContact: '',
  remarks: ''
})

// 表单验证规则
const applyRules = {
  contractId: [
    { required: true, message: '请选择合同', trigger: 'change' }
  ],
  checkoutReason: [
    { required: true, message: '请输入退租原因', trigger: 'blur' },
    { min: 10, message: '退租原因至少10个字符', trigger: 'blur' }
  ],
  expectedCheckoutDate: [
    { required: true, message: '请选择期望退租日期', trigger: 'change' }
  ]
}

// 获取退租申请列表
const fetchCheckoutList = async () => {
  loading.value = true
  try {
    const response = await api.get('/checkout/tenant/list', {
      headers: { info: getToken() }
    })
    if (response.data.code === 200) {
      checkoutList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取退租申请列表失败')
    }
  } catch (error) {
    ElMessage.error('获取退租申请列表失败')
  } finally {
    loading.value = false
  }
}

// 获取有效合同列表
const fetchActiveContracts = async () => {
  try {
    const response = await api.get('/contract/tenant/active', {
      headers: { info: getToken() }
    })
    if (response.data.code === 200) {
      activeContracts.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取有效合同失败:', error)
  }
}

// 提交退租申请
const submitApplication = async () => {
  if (!applyFormRef.value) return
  
  const valid = await applyFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  submitting.value = true
  try {
    const response = await api.post('/checkout/tenant/apply', applyForm.value, {
      headers: { info: getToken() }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('退租申请提交成功')
      showApplyDialog.value = false
      resetForm()
      fetchCheckoutList()
    } else {
      ElMessage.error(response.data.message || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  applyForm.value = {
    contractId: '',
    checkoutReason: '',
    expectedCheckoutDate: '',
    contactPhone: '',
    emergencyContact: '',
    remarks: ''
  }
  applyFormRef.value?.resetFields()
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用昨天之前的日期
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待审核
    1: 'success',  // 已通过
    2: 'danger'    // 已拒绝
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 查看详情
const viewDetail = (item) => {
  // 这里可以实现查看详情的逻辑
  ElMessage.info('查看详情功能待实现')
}

// 页面加载时获取数据
onMounted(() => {
  fetchCheckoutList()
  fetchActiveContracts()
})
</script>

<style scoped>
.checkout-content {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.page-header h2 {
  color: white;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.page-header .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.checkout-list {
  display: grid;
  gap: 20px;
}

.checkout-item {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.checkout-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.checkout-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.contract-info h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 18px;
}

.contract-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.checkout-content-detail {
  margin-bottom: 15px;
}

.checkout-content-detail p {
  margin: 8px 0;
  color: #34495e;
}

.checkout-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
